/*
 * @Author: hexudong 1264275442@qq.com
 * @Date: 2023-08-02 10:22:50
 * @LastEditors: hexudong 1264275442@qq.com
 * @LastEditTime: 2023-08-03 14:25:36
 * @FilePath: /worker_supervision_oa/src/components/NewFileUpload/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Upload, Button, message, Popconfirm, Space } from 'antd';
import { UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import FileOpen from '@/components/FileIframOpen';
import { fetchAssumeRole, frontEndBatch } from './service'
import { md5 } from '@/utils/md5';
import OSS from 'ali-oss'
export interface FileUploadProps {
    value?: any[];
    onChange?: any;
    onLoading?: any;
    max?: number;
    type?: string;
    readOnly?: boolean;
    multiple?: boolean;
    directory?: boolean;
    showClear?: boolean;
    cleardis?: boolean;
    ossEnum?: string;
    href?: string;
    hrefText?: string;
    hrefTaget?: string;
    actionUrl?: string;
    showUploadList?: boolean;
    text?: string;
    disabled?: boolean;
    currentUser?: CurrentUser;
    getSuccess?: any;
    fileList?: any;
    setFileList?: any;
    resourceDTO?:any;
    setResourceDTO?:any
}
import { history, connect } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from '@/models/user';
interface CRef {
    clear: () => void;
}

let prePropsValue: any = [];

let num = 0

const fileType = ['jpg', 'png', 'jpeg', 'gif', 'pdf', 'doc', 'docx'];
const FileUpload = forwardRef<CRef, FileUploadProps>((props, ref) => {
    // const postFileList = props.fileList || [];
    const [postFileList, setPostFileList] = useState<any[]>(props.value || []);
    // const [fileList, setFileList] = useState<any[]>([]);
    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const { ossEnum, actionUrl, showUploadList, text, fileList, setFileList,resourceDTO, setResourceDTO } = props;
    const [showFile, setShowFile] = useState<boolean>(false);
    const [client, setClient] = useState<any>({});
    // const [resourceDTO, setResourceDTO] = useState<any>([]);

    const [loading, setLoading] = useState<boolean>(false)


    // let resourceDTO:any[] = []
    //用useImperativeHandle暴露一些外部ref能访问的属性
    useImperativeHandle(ref, () => ({
        clear
    })
    );

    useEffect(() => {
        setPostFileList(() => {
            return props.value || [];
        });
        setFileList(() => {
            return props.value || [];
        });
        getToken()
    }, [props.value]);

    const propPostChange = (pFs: any) => {
        const { onChange } = props;
        if (onChange) {
            onChange(pFs);
        }
    };
    // 获取Oss token

    const getToken = async () => {
        let res = await fetchAssumeRole();
        if (!res.success && res.errCode == 1000) {
            history.push('/user/login');
            return {};
        }
        if (!res || !res.success) {
            message.error(res.errMsg);
        }
        const ossData = res.data || {};
        console.log(process.env.NODE_ENV, 'process.env.NODE_ENV');
        let url = process.env.NODE_ENV === 'development' ? 'ossmediutestdaily.goodrs.cn' : 'ossworker.jxsrnmg.com'
        const client = new OSS({
            // yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
            region: 'oss-cn-hangzhou',
            // 从STS服务获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
            accessKeyId: ossData.accessKeyId,
            accessKeySecret: ossData.accessKeySecret,
            // 从STS服务获取的安全令牌（SecurityToken）。
            stsToken: ossData.securityToken,
            // 填写Bucket名称。
            // bucket:'https://ossworker.jxsrnmg.com',
            bucket: ossData.bucket,
            cname: true,
            endpoint: ossData.endpoint,
            timeout: 900000
        })
        setClient(client)

    }
    const fetchUpload = async (file: any, idInfo: any,) => {

        const { currentUser } = props
        // let arr = JSON.parse(JSON.stringify(resourceDTO))
        let obj = {
            fileId: idInfo,
            fileName: file.name,
            md5: idInfo.split('.')[0],
            size: file.size,
            userId: currentUser?.userId || null,
            uid: file.uid
        }
        setResourceDTO((files: any) => {
            files.push(Object.assign({ ...obj }));
            return files;
        })
    }
    const putOssObject = async (name: any, file: any, option: any) => {
        try {
            let urlName = 'contracttest/' + name
            const result = await client.put(urlName, file);
            // console.log(result, '--------');
            if (result && result.res) {
                // 上传到服务器
                fetchUpload(file, urlName);
                option.onSuccess();
                file.status = 'done'

            } else {
                file.status = 'err'
            }
        } catch (e) {
            console.log(e);
        }
    }
    const toFrontEndBatch = async () => {

        const { onLoading } = props;
        if (resourceDTO.length == 0) {
            setPostFileList([])
            propPostChange([])
            if (onLoading) {
                onLoading(false);
                setLoading(false)
            }
            return
        }
        let response = await frontEndBatch({ resourceDTO: JSON.stringify(resourceDTO) })
        if (!response.success && response.errCode == 1000) {
            history.push('/user/login');
            return {};
        }
        if (response && response.success) {
            // 上传文件，返回结果，将文件插入到编辑器中
            setPostFileList(response.data)
            propPostChange(response.data)
            if (onLoading) {
                onLoading(false);
                setLoading(false)
            }
        }
    }

    const onChange: any = ({ fileList, file }: any) => {
        // console.log(fileList, file, 'change---fileList');
        const { onLoading } = props;
        if (!loading) {
            if (onLoading) {
                onLoading(true);
                setLoading(true)
            }
        }
        if (file.status == 'done') {
            num = num + 1
            console.log(num, 'num');
        }
        let suc = fileList.every((item: any) => item.status == 'done')
        console.log(suc, 'sucsuc');
        if (suc) {
            toFrontEndBatch()
        }
        setFileList(fileList);

    };

    const clear = () => {


    };
    const onRemove = (file: any) => {
        console.log(file, 'file');
        let index = -1,
            statuIndex = -1;
        const newFileList = fileList.concat();
        postFileList.map((el: any, i: number) => {
            if (el.uid == file.uid) {
                index = i;
            }
        });
        newFileList.map((el: any, i: number) => {
            if (el.uid == file.uid) {
                statuIndex = i;
                el.status = 'remove';
            }
        });
        if (index > -1) {
            setPostFileList((fs) => {
                fs.splice(index, 1);
                console.log(fs, 'fssss');

                return fs;
            });
            propPostChange(postFileList);
            setResourceDTO((files: any) => {
                files.splice(index, 1);
                return files;
            })

        }
        if (statuIndex > -1) {
            newFileList.splice(index, 1);
            setFileList(newFileList);
        }
    };
    const getBase64 = (file: any) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = (error) => reject(error);
        });
    };

    const beforeUpload = (file: any, fileList: any) => {
        // 无法控制显示名称，在onChange中控制
        const isLt12M = file.size / 1024 / 1024 <= 500;
        if (!isLt12M) {
            // file['name'] = '文件大小不能超过 12MB!';
            file.status = 'error';
            message.error('文件大小不能超过 500MB!');
        }
        // console.log(fileList, 'fileList');

        return isLt12M;
    };

    const handlePreview = async (file: any) => {
        if (file.url) {
            if (file.name) {
                const fix = file.name.substring(file.name.lastIndexOf('.') + 1);
                if (fileType.indexOf(fix) >= 0) {
                    window.open(file.url);
                    return;
                }
            } else {
                window.open(file.url);
                return;
            }
        }

        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewVisible(true);
        setPreviewImage(file.url || file.preview);
    };
    const customRequest = (option: any) => {
        console.log(option, 'option');

        let file = option.file
        file.status = 'uploading'
        const typeList = file.name.split('.');
        // 文件类性
        const fileType = typeList[typeList.length - 1];
        let reader = new FileReader();
        reader.readAsDataURL(file); // 读取图片文件
        reader.onload = (e) => {
            let md5Num = md5(reader.result);
            let name = md5Num + '.' + fileType;
            // 上传到oss
            putOssObject(name, file, option);
        };

    }

    return (
        <div style={{ position: 'relative' }}>
            <Space direction="vertical">
                {fileList.length > 0 && props.showClear && (
                    <Popconfirm placement="rightBottom" title="确认全部删除吗？" onConfirm={clear}>
                        <Button
                            danger
                            disabled={fileList.length <= 0 || props.cleardis}
                            icon={<DeleteOutlined />}
                        >
                            一键清空
                        </Button>
                    </Popconfirm>
                )}
                <Upload
                    listType="picture"
                    accept={props.type || ''}
                    fileList={fileList}
                    multiple={props.multiple || true}
                    directory={props.directory || false}
                    disabled={props.readOnly}
                    onPreview={handlePreview}
                    beforeUpload={beforeUpload}
                    onChange={onChange}
                    onRemove={onRemove}
                    maxCount={props.max}
                    customRequest={customRequest}
                    data={{
                        ossEnum,
                    }}
                    showUploadList={typeof showUploadList == 'boolean' ? showUploadList : true}
                >
                    {fileList.length < (props.max || 5) && !props.readOnly && (
                        <>
                            <Button icon={<UploadOutlined />}>{text || '点击上传'}</Button>
                            <a style={{ marginLeft: '20px' }}>支持pdf，图片，word格式</a>
                            <span style={{ color: 'red' }}>加载文件，请耐心等待，请误操作</span>
                        </>

                    )}
                </Upload>
            </Space>
            {props.href && (
                <>
                    {props.hrefTaget == 'open' ? (
                        <a
                            style={{ position: 'absolute', top: '5px', left: '130px' }}
                            onClick={() => {
                                setShowFile(true);
                            }}
                        >
                            {props.hrefText || ''}
                        </a>
                    ) : (
                        <a
                            style={{ position: 'absolute', top: '5px', left: '130px' }}
                            href={props.href}
                            target={props.hrefTaget}
                            download
                        >
                            {props.hrefText || ''}
                        </a>
                    )}
                </>
            )}
            {showFile && (
                <FileOpen
                    title={props.hrefText || ''}
                    fielUrl={props.href || ''}
                    download={2}
                    modalVisible={showFile}
                    onCancel={() => {
                        setShowFile(false);
                    }}
                />
            )}
        </div>
    );
});
export default connect(({ user }: ConnectState) => ({
    currentUser: user.currentUser,
}))(FileUpload);
